#include <iostream>
using namespace std;

void _MergeSort(int* a, int* tmp, int begin, int end)
{
	if (begin >= end)
		return;
	
	int mid = begin + (end - begin) / 2;
	_MergeSort(a, tmp, begin, mid);
	_MergeSort(a, tmp, mid + 1, end);

	int begin1 = begin, end1 = mid;
	int begin2 = mid + 1, end2 = end;
	int k = begin;
	while (begin1 <= end1 && begin2 <= end2)
	{
		if (a[begin1] < a[begin2])
		{
			tmp[k++] = a[begin1++];
		}
		else
		{
			tmp[k++] = a[begin2++];
		}
	}

	while (begin1 <= end1)
	{
		tmp[k++] = a[begin1++];
	}

	while (begin2 <= end2)
	{
		tmp[k++] = a[begin2++];
	}

	//for (int i = begin; i <= end; i++)
	//{
	//	a[i] = tmp[i];
	//}

	memcpy(a + begin, tmp + begin, (end - begin + 1) * sizeof(int));
}

void MergeSort(int* a, int n)
{
	int* tmp = (int*)malloc(sizeof(int) * n);
	if (nullptr == tmp)
	{
		perror("mallc failed");
		exit(-1);
	}

	_MergeSort(a, tmp, 0, n-1);
}

int main()
{
	int a[] = { 1,3,5,7,9,2,8,4,6,0 };
	int n = sizeof(a) / sizeof(a[0]);

	MergeSort(a, n);
	for (auto e : a)
	{
		cout << e << " ";
	}
	cout << endl;

	return 0;
}